﻿#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>

void Gotoxy(int x, int y)
{
	COORD pos = {x, y};
	HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleCursorPosition(output, pos);
}

int IsExitMap(char* mapName)
{
	//Check in folder Maps. 
	//If exist any file (without extension) has the same name as mapName, will return 1 (already exist)
	return 0; // not exist
}

void SaveMap(char* mapName, int **board,  int row, int col)
{
	//Save map to file *.map in Maps folder

	FILE *ptr_file;
	int i,j;
	char* fileName = (char*)malloc(sizeof(char)*120);
	//should be exist folder Maps
	strcpy(fileName,"maps\\");
	strcat(fileName,mapName);
	strcat(fileName,".map");

	ptr_file =fopen(fileName, "w");

	if (ptr_file)
	{
		fprintf(ptr_file,"%d %d\n", row,col);
		for (i = 0; i < row; i++)
		{
			for (j = 0; j < col; j++)
			{
				fprintf(ptr_file,"%d", board[i][j]);

			}	
			fprintf(ptr_file,"\n");
		}

		fclose(ptr_file);
		printf("Save successfully!");
	}
	else
	{
		printf("Save failure!");
	}
	free(fileName);
}

int IsValidName(char* mapName)
{
	// to use that for a file name so:
	// - not longer than 50 charactors
	// - not contain special charactors
	// and more...
	return 1;
}

void InitializeBoard(int **board,  int row, int col)
{
	int i,j;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			board[i][j]=0;

		}		
	}
}

void DisplayBoard(int **board,  int row, int col)
{
	int i,j;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			printf(board[i][j]==0?".":"#");

		}
		printf("\n");
	}
}

void Display()
{
	int i,j, row, column;
	char* mapName;
	int **board;
	system("cls");
	printf("WELCOME TO SNAKE GAME MAP CREATOR STANDALONE FUNCTION DEMO\n");
	printf("==========================================================\n");

	printf(" - Enter map name: ");
	mapName = (char*)malloc(sizeof(char)*100);//100 character can input
	gets(mapName);
	while(!IsValidName(mapName) || IsExitMap(mapName))
	{
		printf(" - Your input invalid, Re-enter map name: ");
		gets(mapName);
	}

	printf(" - Enter map size (row colum):");
	scanf("%d%d",&row,&column);

	board = (int**)malloc(sizeof(int*)*row);
	for (i = 0; i < row; i++)
	{
		*(board + i) = (int*)malloc(sizeof(int)*column);
	}
	InitializeBoard(board, row, column);

	printf(" - Map preview:\n");
	do{
		Gotoxy(0,5);
		DisplayBoard(board, row, column);
		printf(" - Enter island point (row column), -1 -1 to exit:");
		scanf("%d%d",&i,&j);

		if(i<0 && j<0) 
			break;
		if(i>=0 && j>=0 && i<row && j<column)
			board[i][j] = 1;
	} while(i);

	SaveMap(mapName, board, row, column);

	free(mapName);
	for (i = 0; i < row; i++)
	{
		free(*(board + i));
	}
	free(board);
}

int main()
{
	Display();
	getch();
	return 0;
}